package history

import (
    "encoding/json"
    "log"
    "net/http"
)

func HandleHistory(w http.ResponseWriter, r *http.Request, db *Db, currentWorkerCount int32) {
    data := make(map[string]interface{})
    jobs := make([]*JobRecord, 0)
    args := r.URL.Query()
    var since, until, status string
    if u, ok := args["until"]; ok {
        until = u[0]
    } else if s, ok := args["since"]; ok {
        since = s[0]
    }
    if s, ok := args["status"]; ok {
        status = s[0]
    }
    jobs, err := db.Read(since, until, status, 100)
    if err != nil {
        w.WriteHeader(http.StatusServiceUnavailable)
        w.Write([]byte(err.Error()))
        return
    }

    data["currentWorkerCount"] = currentWorkerCount

    if len(jobs) > 0 {
        data["Latest"] = jobs[0].Id
        data["Oldest"] = jobs[len(jobs)-1].Id
    }
    if len(status) > 0 {
        data["Status"] = status
    }

    data["Jobs"] = jobs

    //t, err := template.New("index").Parse(index_template())
    //if err != nil {
    //    w.WriteHeader(http.StatusServiceUnavailable)
    //    w.Write([]byte(err.Error()))
    //    return
    //}

    if currentWorkerCount == 0 {
        w.WriteHeader(http.StatusServiceUnavailable)
    }else{
        w.WriteHeader(http.StatusOK)
    }

    //t.Execute(w, data)

    w.Header().Add("Access-Control-Allow-Origin", "*")
    w.Header().Add("Content-Type", "application/json")
    //buf, err := json.MarshalIndent(data, "", "  ")
    buf, err := json.Marshal(data)
    if err != nil {
        log.Panicf("could not encode api response: %s", err)
    }
    w.Write(buf)
}

// From: {{.Oldest.Format "Jan _2 15:04:05"}} To: {{.Latest.Format "Jan _2 15:04:05"}}
func index_template() string {
    return `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>history</title>
</head>
<body>
<div>
    {{ if .Oldest }}
    <a href="/history?until={{.Oldest}}{{if .Status }}&status={{.Status}}{{ end }}">older</a>
    {{ end }}
    {{ if .Latest }}
    <a href="/history?since={{.Latest}}{{if .Status }}&status={{.Status}}{{ end }}">newer</a>
    {{ end }}
</div>
<table border="1">
    <tr>
        <th>id</th>
        <th>created</th>
        <th>updated</th>
        <th>controller</th>
        <th>worker</th>
        <th>status</th>
        <th>error</th>
    </tr>
    {{range .Jobs}}
    <tr>
        <td>{{.Id}}</td>
        <td>{{.CreatedAt.Format "Jan _2 15:04:05"}}</td>
        <td>{{.UpdatedAt.Format "Jan _2 15:04:05"}}</td>
        <td>{{.Controller}}</td>
        <td>{{.Worker}}</td>
        <td>{{.Status}}</td>
        <td>{{.Error}}</td>
    </tr>
    {{end}}
</table>
</body>
</html>
`
}
